package cn.jsp.dao;

import cn.jsp.domain.Product;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@Repository
public class ProductDao {
  @Autowired
  DataSource dataSource;
  @SneakyThrows
  public List<Product> query(String sql,Object...params){
    List<Product> res=new ArrayList<>();
    try (
            Connection connection = dataSource.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement("select * from stu");
            ResultSet rs = preparedStatement.executeQuery();) {
      while (rs.next()) {
        //把一行ResultSet转为一个Product,ResultSet->Product
        Product product=new Product();
        product.setName(rs.getString("name"));
        product.setPrice(rs.getDouble("price"));
        res.add(product);
      }
    }
    return res;
  }
}
